<?php
/**
 * File: BaseController.class.php
 * Author: camy <375766145@qq.com>
 * Time: 2018/3/18 16:40
 */

namespace Home\Controller;

use Common\Extend\Helper\Exception;
use Common\Extend\Helper\LoginUser;
use Common\Extend\Traits\Authenticate;
use Common\Extend\Traits\JsonReturn;
use Common\Service\User;
use Think\Controller;

class BaseController extends Controller
{
    use JsonReturn, Authenticate;

    protected $viewTemplatePath = 'web';//默认模板
    protected $notAuthActions = [];//免登录方法名

    protected function _initialize()
    {
        //标题
        $this->title = '能投艺科OA系统';
        //判断客户端，设置模板
        if (is_mobile()) {
            $this->viewTemplatePath = 'mobile';
        }
        //身份验证
        if (!in_array(ACTION_NAME, $this->notAuthActions)) {
            $user = $this->authenticate();
            if ($user) {
                //设置已登录用户
                $loginUser = LoginUser::instance();
                $loginUser->setUser($user);
                $this->addCommonParam();
            } else {
                throw new Exception('未登录或登录过期，请重新登录后访问');
            }
        }


    }

    /**
     * 绑定公共参数
     */
    protected function addCommonParam()
    {
        //用户参数
        $loginUser = LoginUser::instance();
        $user = $loginUser->getUser();
        $param['user']['avatar'] = $user['avatar'];
        $param['user']['name'] = $user['name'];
        $param['user']['position'] = $user['position'];
        $param['user']['department'] = $user['department'];
        $param['user']['balance'] = $user['balance'];
        //部门参数
        $deptService = User::instance();
        $param['department'] = $deptService->getDepartmentList();
        $this->assign('commonParam', $param);
    }

    /**
     * 覆写display方法,渲染必须使用render替代display
     */
    protected function render($templateFile = '', $charset = '', $contentType = '', $content = '', $prefix = '')
    {
        $this->theme($this->viewTemplatePath)
            ->display($templateFile, $charset, $contentType, $content, $prefix);
        return true;
    }

    /**
     * 失败操作，跳转错误页面
     * @param string $message
     * @throws Exception
     */
    protected function fail($message = '')
    {
        $message = empty($message) ? C('ERROR_MESSAGE') : $message;
        throw new Exception($message);
    }

}